(function () {
	//自定义true标签对象
	function trueTags(){}
	trueTags.prototype = {
		//弹出窗体
		getDomHtml:function(){
			return '<div class="tw-window tw-winpn tw-window-dataImport-tag">\
				<div class="tw-close-cross">X</div>\
				<div class="tw-window-con">\
					<div class="tw-layout-title">插入标签</div>\
					<div class="tw-import-wrap">\
						<div class="tw-tabs JS_tabs">\
							<div class="tw-tabs-body" style="overflow-y:auto">\
								<div class="tw-tabs-con zhibiao">\
									<div class="tw-form tw-pro">\
										<div class="row">\
											<label>选择指标:</label>\
											<div>\
												<select class="JS_zhibiao form-control input-sm chosen-select"></select>\
											</div>\
										</div>\
									</div>\
								</div>\
								<div class="tw-tabs-con yaosu">\
									<div class="tw-form tw-pro">\
									</div>\
								</div>\
								<div class="tw-tabs-con group">\
									<div class="tw-form tw-pro">\
										<div class="row">\
										</div>\
									</div>\
								</div>\
								<div class="tw-tabs-con timer">\
									<div class="tw-form tw-pro">\
									</div>\
									<div class="tw-btnw">\
										<span class="tw-btnm custom save JS_next_step step4" style="">预览</span>\
									</div>\
								</div>\
								<div class="tw-tabs-con function result notClear">\
									<div class="tw-form tw-pro" style="display:none">\
										<p class="tw-marginTopLine"><label style="margin-left: 10px;">计算公式:</label><input class="JS_inputResult" type="text" placeholder="计算公式"><span class="JS_btnTagTest btn btn-primary btn-xs">运行</span> <span class="JS_btnTagReset btn btn-primary btn-xs">重置</span></p>\
									</div>\
									<p><label style="margin-top:10px;margin-left:10px">预览结果:</label><span class="JS_tagValue tags"></span></p>\
									<div class="tw-btnw">\
										<span class="tw-btnm custom save JS_next_step step5">保存</span>\
									</div>\
								</div>\
							</div>\
						</div>\
					</div>\
				</div>\
			</div>';
		},
		
		//时间选择的结构
		getTimerHtml:function(){
			//当年
			var yearNow = new Date().getFullYear();
			this.yearNow = yearNow;
			//当月
			var monthNow = new Date().getMonth()+1;
			this.monthNow = monthNow;
			var condMonthOption = '';
			for ( var i = 1; i<=12; i++ ){
                condMonthOption += '<option value ="'+ i +'">'+ i +'</option>';
            }
			condMonthOption += '<option value ="'+ this.nowM +'">当前月</option>';
			var condYearOption = '';
			for ( var i = (yearNow-5); i<=(yearNow+5); i++ ){
                condYearOption += '<option value ="'+ i +'">'+ i +'</option>';
            }
			condYearOption += '<option value ="'+ this.nowY +'">当前年</option>';
			var html = '<div class="row">\
						<label>选择类型:</label>\
						<div class="small">\
							<select class="JS_timerTyper form-control input-sm chosen-select chosen-select">\
								<option value="year">年度</option>\
								<option value="month">月度</option>\
							</select>\
						</div>\
						<label>选择年份:</label>\
						<div class="small">\
							<select class="JS_timerEndYear form-control input-sm chosen-select chosen-select">\
							'+condYearOption+'\
							</select>\
						</div>\
						<label>选择月份:</label>\
						<div class="small">\
							<select class="JS_timerEndMonth form-control input-sm chosen-select chosen-select">\
							'+condMonthOption+'\
							</select>\
						</div>\
					</div>';
			return html;
		},
		
		//对象初始化
		init:function(options){
			var that = this;
			//true标签的配置
			this.config = {
				//接口根路径
				basePath:'/trueMAEC',//http://192.168.0.25:5012
				//接口参数
				deptid:'{BFA80019-0000-0000-432B-267E0000000E}',
				//debug开关，开启后用本地随机数据
				debugEnable:false//true
			};
			//全局true标签num
			this.globalNum = 1;
			//随机true标签id前缀
			this.idPrefix = 'tags_' + Math.random().toString().replace('.', '') + '_';
			//是否进入编辑状态
			this.isEditing = false;
			//临时数据存储
			this.tmpData = {};
			//封装好的最终数据
			this.dataJSON = {};
			//当前编辑对象ID
			this.currentId = false;
			//当前年月函数
			this.nowY = '当前年';//'year(sysdate())';
			this.nowM = '当前月';//'month(sysdate())';
			//合并配置
			if(options){
				this.updateOption(options);
			}
			
			//定义弹出层大小
			this.updateScreenSize();
			
			//页面渲染
			this.createCustomWraps();
			
			//获取wangEditor构造函数
			this.WE = window.wangEditor;
			this.createCustomToMenu(function(reParams){
				//点击菜单事件
		        reParams.menu.clickEvent = function (e) {
		        	//编辑状态=否
		        	that.clearCustomWrap(0);
		        	that.clearFunctionWrap();
		        	that.resetLayerTab({index:0});
		        	that.isEditing = false;
	            	that.currentId = false;
		        	that.layerIn({e:e,editor:reParams.editor});
		        }
			});
			
			//拓展tag的自定义工具
			this.WE.plugin(function(){
				return that.customToolPlugin({that:that,this:this});
			});
			
			return this;
		},
		
		//覆盖配置
		updateOption:function(options){
			this.config = $.extend(true, this.config, options);
		},
		
		//更新屏幕尺寸
		updateScreenSize:function(){
			this.layerSize = this.getPageSize();
		},
		
		//页面初始化
		createCustomWraps:function(){
			var that = this;
			
			var temp = $('#twEditor').find('.tw-window-dataImport-tag');
			if(temp && temp.length>0){
				//$('#twEditor').find('.tw-window-dataImport-tag').remove();
			}else{
				$('#twEditor').append(this.getDomHtml());
			}
			
		    //绑定对象内变量
		    this.customWrapsAligin();
		    
			//左侧标签初始化
			this.$tabsWrap.slide({
				titCell:".tw-tabs-head li"
				,mainCell:".tw-tabs-body"
				,trigger:"click"
			});
		},
		
		//dom变量赋值
		customWrapsAligin:function(){
			this.$mainWrap      = $('.tw-window-dataImport-tag');
			this.$tabsWrap      = $('.tw-window-dataImport-tag').find('.JS_tabs');
			this.$zhibiaoWrap   = $('.tw-window-dataImport-tag').find('.JS_zhibiao');
			this.$groupWrap     = $('.tw-window-dataImport-tag').find('.JS_group');
			this.$yaosuWrap     = $('.tw-window-dataImport-tag').find('.JS_yaosu');
			this.$timer         = $('.tw-window-dataImport-tag').find('.tw-tabs-con.timer');
			this.$timerTypeWrap = $('.tw-window-dataImport-tag').find('.JS_timerType');
			this.$yearWrap      = $('.tw-window-dataImport-tag').find('.JS_timerYear');
			this.$monthWrap     = $('.tw-window-dataImport-tag').find('.JS_timerMonth');
			this.$quarterWrap   = $('.tw-window-dataImport-tag').find('.JS_timerQuarter');
			this.$functionWrap  = $('.tw-window-dataImport-tag').find('.tw-tabs-con.function');
			this.$resultWrap    = $('.tw-window-dataImport-tag').find('.tw-tabs-con.result');
			this.$step1         = $('.tw-window-dataImport-tag').find('.JS_next_step.step1');
			this.$step2         = $('.tw-window-dataImport-tag').find('.JS_next_step.step2');
			this.$step3         = $('.tw-window-dataImport-tag').find('.JS_next_step.step3');
			this.$step4         = $('.tw-window-dataImport-tag').find('.JS_next_step.step4');
			this.$step5         = $('.tw-window-dataImport-tag').find('.JS_next_step.step5');
		},
		
		//弹出数据编辑层
		layerIn:function(params){
			//params.e, params.editor
			this.tmpData.editorParams = params;
			var that = this;
			
			this.updateScreenSize();
			
			//打开弹出层
			layer.open({
				type:1,
				title:false,
				closeBtn:0,
				shadeClose:false,
				area:[that.layerSize[2]-40+'px', that.layerSize[3]-40+'px'],
				skin:"layui-layer-nobg tw-window-show",
				content:that.$mainWrap,
				success:function(layero, index){
					//loading start
		        	that.loadLayerIdx = layer.load(1);
		        	
					that.tmpData.layerIdx = index;
					//close
					that.bindEvent({
						obj:$('.tw-close-cross'),
						name:'click',
						events:function(){
							//保存数据
							that.isEditing = false;
			            	that.currentId = false;
			            	that.tmpData = {};
							layer.close(index);
							clearInterval(that.myTimer);
						}
					})
					//edit
					if(that.isEditing){
						that.resetLayerTab({index:4});
						//计算公式和预览结果数据导入
						that.clearFunctionWrap();
						that.importResult();
					}
					//接口数据初始化
					that.zhibiaoInit();
				}
			})
		},
		
		//指标数据初始化
		zhibiaoInit:function(){
			var that = this;
			this.getJSON({
				url:that.config.basePath + "/trueDataController/getModelList.do?deptid="+that.config.deptid,
				callback:function(result){
					if(result && result.data && result.data.length>0){
						var tables = result.data
						,tableOption = '';
						for(var i=0,l=tables.length;i<l;i++){
							var selected = '';
							if(that.isEditing){
								if(that.tmpData.step1 == tables[i].modelId){
									selected = 'selected';
								}
							}
			        		tableOption += '<option '+selected+' value="'+ tables[i].modelId +'" data-tableName="'+ tables[i].tableName +'" data-tbKey="'+i+'">'+tables[i].modelName+'</option>';
			        	}
			        	that.$zhibiaoWrap.empty().append(tableOption);
			        	that.chosenInit(that.$zhibiaoWrap);
			        	//绑定change事件//标记初始化成功状态
			        	that.bindEvent({
			        		obj:that.$zhibiaoWrap,
			        		name:'change',
			        		events:function(){
			        			var val = $(this).val();
			        			if(val=='error'){
			        				that.$tabsWrap.find(".tw-tabs-head li").attr('load','no');
			        			}else{
			        				that.$tabsWrap.find(".tw-tabs-head li.on").attr('load','yes');
			        			}
		        				that.clearCustomWrap(0);

		        				var idx = parseInt(that.$zhibiaoWrap.find('option:selected').attr("data-tbkey"));
		        				//存储对象
		        				that.tmpData.step1 = that.$zhibiaoWrap.find('option:selected').val();
		        				that.tmpData.step1Data = {data:result,idx:idx};
		        				that.tmpData.tableName = that.$zhibiaoWrap.find('option:selected').attr('data-tablename');
		        				that.tmpData.step1Name = that.$zhibiaoWrap.find('option:selected').text();
		        				
		        				that.yaosuInit();
			        		}
			        	})
			        	
			        	that.$zhibiaoWrap.trigger('change');
			        	
			        	//左右同步效果
//                      that.myTimer = setInterval(function(){
//                      	var idx = that.$tabsWrap.find('.tw-tabs-head li.on').attr('data-type');
//                      	that.$tabsWrap.find('.tw-tabs-body .tw-tabs-con').eq(idx).addClass('active').siblings('.tw-tabs-con').removeClass('active');
//                      }, 100);

                        that.bindEvent({
                        	obj:that.$tabsWrap.find('.tw-tabs-body .tw-tabs-con'),
                        	name:'click',
                        	events:function(){
                        		var idx = $(this).index();
                        		that.$tabsWrap.find('.tw-tabs-head li[data-type="'+idx+'"]').addClass('on').siblings('li').removeClass('on');
                        	}
                        })
			        	
			        	//loading ok
			        	layer.close(that.loadLayerIdx);
			        	
					}else{
						//loading error end
						layer.close(that.loadLayerIdx);
						
						//关闭
						$('.tw-close-cross').trigger('click');
						layer.msg('获取数据异常');
					}
				},
				errorFun:function(){
					//todo
					that.$tabsWrap.find(".tw-tabs-head li.on").attr('load','no');
					
					//loading error end
					layer.close(that.loadLayerIdx);
					//关闭
					$('.tw-close-cross').trigger('click');
					layer.msg('获取数据异常');
				}
			})
		},
		
		//要素数据初始化
		yaosuInit:function(){
			var that = this;
			var modelId = this.tmpData.step1;
			this.getJSON({
				url:that.config.basePath + "/trueDataController/getFieldList.do?modelId="+modelId,
				callback:function(result){
					//渲染要素模块
					var field = result;
					if(field.data && field.data.fields){
						var fieldTable = '';
                        var fields = field.data.fields;
                        var fieldItem = ''
                        if(fields.length>0){
                        	var h = '<div class="row">\
										<label>选择要素:</label>\
										<div>\
											<select class="JS_yaosu form-control input-sm chosen-select"></select>\
										</div>\
									</div>';
	                        //选择要素
	                        var tables = fields
							,tableOption = '';
							for(var i=0,l=tables.length;i<l;i++){
								var selected = '';
								if(that.isEditing){
									if(tables[i].name == that.tmpData.step3){
										selected = 'selected';
									}
								}
				        		tableOption += '<option '+selected+' value="'+ tables[i].name +'">'+tables[i].note+'</option>';
				        	}
							that.$tabsWrap.find('.tw-tabs-con.yaosu .tw-form').empty().append(h);
							that.customWrapsAligin();
							that.$yaosuWrap.empty().append(tableOption);
							that.chosenInit(that.$tabsWrap.find('select.JS_yaosu'));
							//绑定change事件
							that.bindEvent({
								obj:that.$yaosuWrap,
								name:'change',
								events:function(){
									var sob = $(this).find('option:selected');
									if(sob && sob.length>0){
										var val = sob.val();
										if(val!=='error'){
											that.tmpData.step3 = val;
											that.tmpData.step3Note = sob.text();
											that.$tabsWrap.find(".tw-tabs-head li.on").attr('load','yes');
										}else{
											that.tmpData.step3 = null;
											that.tmpData.step3Note = null;
											that.$tabsWrap.find(".tw-tabs-head li.on").attr('load','no');
										}
									}
									that.groupInit();
								}
							})
							
							that.$yaosuWrap.trigger('change');
                        }
                   	}
				},
				errFun:function(){
					that.$yaosuWrap.empty();
				}
			})
		},
		
		//分组数据初始化
		groupInit:function(){
			var that = this;
			var params = this.tmpData.step1Data;
			var result = params.data,
			idx = params.idx;
			if(result && result.data && result.data.length>0){
				if(result.data[idx] && result.data[idx].tyzdxList && result.data[idx].tyzdxList.length>0){
					var groupdata = result.data[idx].tyzdxList
					,groupItem = '';
					var groups = groupdata;
			        //遍历分组
					for(var i=0,l=groups.length;i<l;i++){
						var groupHD = '<label>'+groups[i].name+':</label>';
		                var groupId = groups[i].id;
		                var groupBD = '<option value="error"></option>';
		                var mxs = groups[i].mxlist;
		                for(var j=0,cl=mxs.length;j<cl;j++){
			        		var selected = '';
		                	if(that.isEditing){
		                		if(mxs[j].guid == that.tmpData.step2){
		                			selected = 'selected';
		                		}
		                	}
		                	groupBD += '<option '+selected+' value="'+ mxs[j].guid +'">'+mxs[j].zbmc+'</option>';
		                }
		                groupItem += '<div class="row">'+ groupHD +'<div><select class="JS_group form-control input-sm chosen-select">'+ groupBD +'</select></div></div>';
					}
					that.$tabsWrap.find('.tw-tabs-con.group .tw-form').empty().append(groupItem);
					that.customWrapsAligin()
					that.chosenInit(that.$tabsWrap.find('.tw-tabs-con.group .tw-form select'));
					//绑定change事件
					that.bindEvent({
						obj:that.$tabsWrap.find('.tw-tabs-con.group .tw-form select'),
						name:'change',
						events:function(){
							if($(this).val()!=='error'){
								$(this).parentsUntil('.row').parent('.row').siblings('.row').find('select').val('error').trigger('chosen:updated');
							}
							//更新绑定变量
	        				that.customWrapsAligin();
	        				var os = that.$groupWrap.find('option:selected');
	        				var step2value = ''
        					,step2Name = '';
        					$.each(os, function(i,e) {
        						if(e.value!=='error'){
        							step2value = e.value;
        							step2Name = e.innerHTML;
        							
		        					that.tmpData.step2 = step2value;
		        					that.tmpData.step2Name = step2Name;
        						}
        					});
        					
							that.timerInit();
						}
					})
					if(that.isEditing){
						that.$tabsWrap.find('.tw-tabs-con.group .tw-form select').trigger('chosen:updated');
					}
					that.$tabsWrap.find('.tw-tabs-con.group .tw-form select').trigger('change');
					
				}
			}
		},
		
		
		
		//时间数据初始化
		timerInit:function(){
			var html = this.getTimerHtml();
			this.$tabsWrap.find('.tw-tabs-con.timer .tw-form').empty().append(html);
			
			if(this.isEditing){
				this.$tabsWrap.find('select.JS_timerEndMonth').val(this.tmpData.endTime);
			}else{
				this.$tabsWrap.find('select.JS_timerEndYear').val(this.yearNow);
//				this.$tabsWrap.find('select.JS_timerEndMonth').val(this.monthNow);
			}
			
			this.chosenInit(this.$tabsWrap.find('select.JS_timerTyper'));
			this.chosenInit(this.$tabsWrap.find('select.JS_timerEndYear'));
			this.chosenInit(this.$tabsWrap.find('select.JS_timerEndMonth'));
			//更新绑定dom对象
			this.customWrapsAligin();
			
			//绑定change关联事件
			var that = this;
			this.bindEvent({
				obj:that.$tabsWrap.find('.JS_timerTyper'),
				name:'change',
				events:function(){
					var val = $(this).val();
					that.tmpData.endTimeTyper = val;
					
					if(that.tmpData.endTimeTyper=='year'){
						that.$tabsWrap.find('.JS_timerEndMonth').parent('.small').prev('label').hide();
						that.$tabsWrap.find('.JS_timerEndMonth').parent('.small').hide();
					}
					if(that.tmpData.endTimeTyper=='month'){
						that.$tabsWrap.find('.JS_timerEndMonth').parent('.small').prev('label').show();
						that.$tabsWrap.find('.JS_timerEndMonth').parent('.small').show();
					}
					that.$tabsWrap.find('.JS_timerEndMonth').trigger('chosen:updated');
				}
			})
			this.bindEvent({
				obj:that.$tabsWrap.find('.JS_timerEndYear'),
				name:'change',
				events:function(){
					var val = $(this).val();
					if(val!=='当前年'){
						that.$tabsWrap.find('select.JS_timerEndMonth').val(1).trigger('change').trigger('chosen:updated');
					}
					that.tmpData.endYear = val;
				}
			})
			this.bindEvent({
				obj:that.$tabsWrap.find('.JS_timerEndMonth'),
				name:'change',
				events:function(){
					var val = $(this).val();
					if(val=='当前月'){
						that.$tabsWrap.find('select.JS_timerEndYear').val('当前年').trigger('change').trigger('chosen:updated');
					}
					that.tmpData.endTime = val;
				}
			})
			
			if(that.isEditing){
				that.$tabsWrap.find('.JS_timerTyper').val(that.tmpData.endTimeTyper);
				that.$tabsWrap.find('.JS_timerEndYear').val(that.tmpData.endYear);
				that.$tabsWrap.find('.JS_timerEndMonth').val(that.tmpData.endTime);
				that.$tabsWrap.find('.JS_timerTyper').trigger('chosen:updated');
				that.$tabsWrap.find('.JS_timerEndYear').trigger('chosen:updated');
				that.$tabsWrap.find('.JS_timerEndMonth').trigger('chosen:updated');
			}
			
			that.$tabsWrap.find('.JS_timerTyper').trigger('change');
			that.$tabsWrap.find('.JS_timerEndYear').trigger('change');
			that.$tabsWrap.find('.JS_timerEndMonth').trigger('change');
			
			//绑定step事件
			this.bindEvent({
				obj:that.$tabsWrap.find('.JS_next_step.step4'),
				name:'click',
				events:function(){
					if(!that.tmpData.step2 || that.tmpData.step2==''){
						layer.msg('分组必选');
						that.$tabsWrap.find(".tw-tabs-head li.on").attr('load','no');
					}else {
						//存储
						that.tmpData.step4 = that.tmpData.endTime;
						var y = that.tmpData.endYear == that.nowY ?'当前':that.tmpData.endYear;
						var m = that.tmpData.endTime == that.nowM ?'当前':that.tmpData.endTime;
						if(that.tmpData.endTimeTyper=='month'){
							that.tmpData.step4Tips = y +'年'+ m +'月';
						}
						if(that.tmpData.endTimeTyper=='year'){
							that.tmpData.step4Tips = y +'年';
						}
						
						that.$tabsWrap.find(".tw-tabs-head li.on").attr('load','yes');
						
        				//测试创建计算因子
        				that.testResultJson();
					}
				}
			})
		},
		
		chosenInit:function(obj){
			obj.chosen({
        		lang:'zh_cn'//简体中文
        		,allow_single_deselect:true//可取消
        		,disable_search:true//禁用检索
        		,drop_direction:'down'//向下
        		,width:'100%'
			});
		},
		
		//编辑时的导入工作
		importResult:function(){
			var that = this;
			var fixedJSON = this.dataJSON[this.currentId].functions;
			
			this.$functionWrap.find('.tw-form.tw-pro .paramval-item').remove();
			
			if(fixedJSON){
				var paramJSON = fixedJSON.param;
				var blocks = '';
				$.each(paramJSON[0], function(i,e) {
					var tmp = {};
					tmp[i]=e;
					blocks += '<div class="paramval-item" data-tips="'+that.tmpData.tips[that.currentId][i]+'">\
						<span class="JS_btnDelParam delparam" style="display: none;">\
							<i class="fa fa-close"></i>\
						</span>\
						<span class="JS_txtClick">'+i+'</span>\
						<textarea style="display:none">'+JSON.stringify(tmp)+'</textarea>\
					</div>';
				});
				
				//公式
				this.$functionWrap.find('.tw-form.tw-pro').prepend(blocks);
				this.$functionWrap.find('.tw-form.tw-pro').find('.JS_inputResult').val(fixedJSON.result.tag);
				this.$functionWrap.find('.JS_tagValue').text(this.dataJSON[this.currentId].tmpData.result);
				this.bindResultEvents();
			}else{
				this.$functionWrap.find('.tw-form.tw-pro').find('.JS_inputResult').val('');
				this.$functionWrap.find('.JS_tagValue').text('');
			}
		},
		
		//单个结果json的生成
		testResultJson:function(){
			var data = this.tmpData;
			var tips = data.step1Name+'，'+data.step2Name+'，'+data.step3Note+'，'+data.step4Tips;
			var _month = data.step4.month
			,_year = data.step4.year
			,_quarter = data.step4.quarter
			,_guId = data.step2
			,_groupId = data.step1;
			if(data.endTimeTyper=='month'){
				//var _condition = {'month': "='"+data.endTime+"'", 'year': "='"+data.endYear+"'", 'season': '', 'mxzbid': "='"+_guId+"'", 'zbid': "='"+_groupId+"'"};
				if(data.endTime=='当前月'){
					var _condition = {
					'date':"='"+data.endTime+"'",
					'mxzbid': "='"+_guId+"'", 'zbid': "='"+_groupId+"'"};
				}else{
					var _condition = {
					'date':"='"+data.endYear+'-'+data.endTime+"'",
					'mxzbid': "='"+_guId+"'", 'zbid': "='"+_groupId+"'"};
				}
			}
			if(data.endTimeTyper=='year'){
				var _condition = {'month': '', 'year': "='"+data.endYear+"'", 'season': '', 'mxzbid': "='"+_guId+"'", 'zbid': "='"+_groupId+"'"};
				var _condition = {
					'date':"='"+data.endYear+"'",
					'mxzbid': "='"+_guId+"'", 'zbid': "='"+_groupId+"'"};
			}
			var _tableName = data.tableName;
			var _fileNote = data.step3Note;
			var _fieldName = data.step3;
			if(this.currentId!==false){
				var currentId = this.currentId;
				var paramJSON = this.dataJSON[currentId].functions.param;
				//TODO:new T
				//this.tmpData.tipsNum++;
				var num = this.tmpData.tipsNum;
				this.tmpData.tips[currentId]['T'+num] = tips;
				paramJSON[0]['T'+num] = {
					'table': _tableName, 'note': _fileNote, 'field':_fieldName, 'condition':_condition
				};
			}else{
				this.currentId = this.getUniqeId();
				var currentId = this.currentId;
				this.tmpData.tipsNum = 1;
				this.tmpData.tips = {};
				this.tmpData.tips[currentId] = {};
				this.tmpData.tips[currentId]['T'+this.tmpData.tipsNum] = tips;
				var paramJSON = [];
				paramJSON[0] = {};
				paramJSON[0]['T'+this.tmpData.tipsNum] = {
					'table': _tableName, 'note': _fileNote, 'field':_fieldName, 'condition':_condition
				};
			}
			
			var fixedJSON = {
				'param' : paramJSON,
				'type': 1,
				'result': {
					'tag':''//T1+T2
				}
			};
			var that = this;
			this.dataJSON[currentId] = {
				functions:fixedJSON,
				tmpData:that.tmpData
			};
			var str = JSON.stringify(fixedJSON);
			//console.log(str);
			
			var blocks = '';
			$.each(paramJSON[0], function(i,e) {
				var tmp = {};
				tmp[i]=e;
				blocks += '<div class="paramval-item" data-tips="'+that.tmpData.tips[currentId][i]+'">\
					<span class="JS_btnDelParam delparam" style="display: none;">\
						<i class="fa fa-close"></i>\
					</span>\
					<span class="JS_txtClick">'+i+'</span>\
					<textarea style="display:none">'+JSON.stringify(tmp)+'</textarea>\
				</div>';
			});
			//公式
			this.$functionWrap.find('.tw-form.tw-pro .paramval-item').remove();
			this.$functionWrap.find('.tw-form.tw-pro').prepend(blocks);
			
			this.bindResultEvents();
			
			//TODO:暂时先不计算公式
			this.$tabsWrap.find('.JS_inputResult').val('T1');
			this.$tabsWrap.find('.JS_btnTagTest').trigger('click');
		},
		
		//计算和结果部分事件绑定
		bindResultEvents:function(){
			var that = this;
			var fixedJSON = this.dataJSON[this.currentId].functions;
			//hover
			this.$functionWrap.find(".paramval-item").off('hover');
			this.$functionWrap.find(".paramval-item").hover(function(){
				var follow = this;
				$(this).find('.JS_btnDelParam').show();
				//tips
				layer.tips($(follow).attr('data-tips'), follow, {tips:3});
			},function(){
				$(this).find('.JS_btnDelParam').hide();
				layer.closeAll('tips');
			})
			
			//click
			this.$functionWrap.find(".JS_txtClick").off('click');
			this.$functionWrap.find(".JS_txtClick").click(function(){
				var _last = that.$tabsWrap.find('.JS_inputResult').val();
				that.$tabsWrap.find('.JS_inputResult').val(_last+$(this).text());
				that.$tabsWrap.find('.JS_inputResult').trigger('focus');
				//结果清空需要重新计算
				that.$tabsWrap.find('.tw-tabs-con.result .JS_tagValue').text('');
			})
			
			//reset
			this.$functionWrap.find('.JS_btnTagReset').off('click').click(function(){
				that.$tabsWrap.find('.JS_inputResult').val('');
				//结果清空需要重新计算
				that.$tabsWrap.find('.tw-tabs-con.result .JS_tagValue').text('');
			})
			
			//delete
			this.$functionWrap.find(".JS_btnDelParam").off('click');
			this.$functionWrap.find(".JS_btnDelParam").click(function(){
				var deleteTargetT = $(this).next('.JS_txtClick').text();
				$(this).parent('.paramval-item').remove();
				that.$tabsWrap.find('.JS_inputResult').val('');
				//TO:将对象中数据同步删除
				var obj = that.dataJSON[that.currentId].functions.param[0];
				var newobj = {};
				$.each(obj, function(i,e) {
					if(i!==deleteTargetT){
						newobj[i] = e;
					}
				});
				that.dataJSON[that.currentId].functions.param[0] = newobj;
				//TO:删除tips
				var tipsobj = that.tmpData.tips[that.currentId];
				var newtipsobj = {};
				$.each(tipsobj, function(i,e) {
					if(i!==deleteTargetT){
						newtipsobj[i] = e;
					}
				});
				that.tmpData.tips[that.currentId] = newtipsobj;
//				console.log(that,this);
				//结果清空需要重新计算
				that.$tabsWrap.find('.tw-tabs-con.result .JS_tagValue').text('');
			})
			
			//运行公式
			this.$functionWrap.find(".JS_btnTagTest").off('click');
			this.$functionWrap.find(".JS_btnTagTest").click(function(){
				var value = $.trim(that.$tabsWrap.find('.JS_inputResult').val())
				if(value==''){
					layer.msg('计算公式不能为空');
					return false;
				}
				
				//往接口传数据测试结果
				//载入公式
				fixedJSON.result.tag = value;
				//转码
				var str = JSON.stringify(fixedJSON);
				that.getJSON({
					data:str,
					url:that.config.basePath + "/formulaController/getResult.do?function="+encodeURIComponent(str),
					callback:function(result){
						if(that.config.debugEnable){
							var val = 10 + (Math.random()*100).toFixed(2);
						}else{
							//console.log(result);
							if(result.success){
								var val = result.data[0].tag;
							}else{
								var val = '计算结果失败';
							}
						}
						that.tmpData.result = val;

        				//预览结果
						that.$resultWrap.find('.JS_tagValue').text(that.tmpData.result);
		            	console.log(that);
        				
        				//最终确认生成标签
        				$('.JS_next_step.step5').off('click');
        				$('.JS_next_step.step5').click(function(){
        					if(!that.tmpData.result){
        						layer.msg('请先运行计算公式');
        						return false;
        					}
        					if(that.isEditing){
        						var $delete = $('.wangeditor-menu-img-trash-o');
								$delete.trigger('click');
        					}
        					//insert
                            var s = '<p><b class="tags" data-id="'+ that.currentId +'">'+ that.tmpData.result
                            +'<span class="tagjson"><!--TrueDATA['+ str +']--></span>'
                            +'</b></p>';
                            // 执行命令
                            var o = that.tmpData.editorParams;
                            o.editor.command(o.e, 'insertHtml', s);
                            
							//保存数据
							that.isEditing = false;
							if(!that.dataJSON[that.currentId]){
								that.dataJSON[that.currentId] = {};
							}
							that.dataJSON[that.currentId].tmpData = that.tmpData;
			            	
			            	//TODO:json加入文章数据相关存储与读取
			            	
                            //close layer
                            layer.close(that.tmpData.layerIdx);
                            
		            		that.currentId = false;
			            	that.tmpData = {};
			            	
							clearInterval(that.myTimer);
        				})
					},
					errorFun:function(result){
						if(that.config.debugEnable){
							this.callback(result);
						}else{
//							console.log(result);
							layer.msg(result.error);
						}
					}
				})
			})
		},
		
		getDataByFun:function(params){
			var that = this;
//			var str = JSON.stringify(params.funJson);
			var str = params.funJson;
			that.getJSON({
				data:str,
				url:that.config.basePath + "/formulaController/getResult.do?function="+encodeURIComponent(str),
				callback:function(result){
					params.callback(result);
				}
			})
		},
		
		//重置容器内容
		clearCustomWrap:function(start){
			if(!start){
				start = 0;
			}
			this.$tabsWrap.find('.tw-tabs-con:gt('+start+')').not('.notClear').find('.tw-form').empty();
//			this.$tabsWrap.find('.tw-tabs-con:gt('+start+')').not('.notClear').find('.tw-btnw .tw-btnm').hide();
		},
		
		//清空运算公式和结果
		clearFunctionWrap:function(){
        	this.$tabsWrap.find('.tw-tabs-con.function').find('.paramval-item').remove();
        	this.$tabsWrap.find('.tw-tabs-con.function').find('.JS_inputResult').val('');
        	this.$tabsWrap.find('.tw-tabs-con.function').find('.JS_tagValue').text('');
		},
		
		//切换tab
		resetLayerTab:function(params){
			this.$tabsWrap.find('.tw-tabs-head li:eq('+params.index+')').addClass('on').siblings('li').removeClass('on');
			this.$tabsWrap.find('.tw-tabs-head li:eq('+params.index+') a').trigger('click');
		},
		
		//绑定事件
		bindEvent:function(params){
			params.obj.off(params.name).on(params.name,params.events);
		},
		
		//重新封装ajax请求数据函数
		getJSON:function(params){
			var that = this;
			$.ajax({
	            type:"POST",
	            dataType:"jsonp",
	            data:params.data?params.data:'',
	            jsonp:"callback",
	            url: params.url,
	            cache: false,
	            async: false,
	            success:function(result){
	            	if(result && (result.error==null) && (result.success==true) && result.data){
			    		//pass
			    		if(params.callback){
			    			params.callback(result);
			    		}
			    	}else{
			    		//ajax data error
			    		console.log('getJSON Error', params);
			    		if(params.errorFun){
			    			params.errorFun(result);
			    		}
			    	}
		        },
		        error:function(){
		        	if(params.errorFun){
		    			params.errorFun();
		    		}
		        }
		  	});
		},
		
		//生成唯一ID
		getUniqeId:function(){
			return this.idPrefix + (this.globalNum++);
		},
		
		//注册trueTags菜单按钮
		createCustomToMenu:function(callback){
			var that = this;
			that.WE.createMenu(function (check) {
				var menuId = 'tags';
		        if (!check(menuId)) {
		            return;
		        }
		        var editor = this;
		        // 创建 menu 对象
		        var menu = new that.WE.Menu({
		            editor: editor,
		            id: menuId,
		            title: '插入标签',
		            // 正常状态和选中装下的dom对象，样式需要自定义
		            $domNormal: $('<a href="#" tabindex="-1"><i class="wangeditor-custom-icon-tags"></i></a>'),
		            $domSelected: $('<a href="#" tabindex="-1" class="selected"><i class="wangeditor-custom-icon-tags"></i></a>')
		        });
		        // 增加到editor对象中
		        editor.menus[menuId] = menu;
		        callback({menu:menu,editor:editor});
			})
		},
		
		//对于自定义标签的拓展插件
		customToolPlugin:function(params){
			var that = params.that;
			var editor = params.this;
	        var txt = editor.txt;
	        var $txt = txt.$txt;
	        // 说明:设置了 max-height 之后，$txt.parent() 负责滚动处理
	        var $currentTxt = editor.useMaxHeight ? $txt.parent() : $txt;
	        var $currentTag;
	
	        // 用到的dom节点
	        var isRendered = false;
	        var $toolbar = $('<div class="txt-toolbar"></div>');
	        var $triangle = $('<div class="tip-triangle"></div>');
	        var $delete = $('<a href="#"><i class="wangeditor-menu-img-trash-o"></i></a>');
	        var $edit = $('<a href="#"><i class="wangeditor-custom-icon-edit"></i></a>');
	        
	        // 渲染到页面
	        function render() {
	            if (isRendered) {
	                return;
	            }
	            
	            // 绑定事件
	            bindEvent();
	
	            // 拼接 渲染到页面上
	            $toolbar.append($triangle)
	                    .append($delete)
	                    .append($edit);
	            editor.$editorContainer.append($toolbar);
	            isRendered = true;
	        }
	        
	        // 绑定事件
	        function bindEvent() {
	            // 统一执行命令的方法
	            var commandFn;
	            function command(e, callback) {
	                if (commandFn) {
	                    editor.customCommand(e, commandFn, callback);
	                }
	            }
	
	            // 删除
	            $delete.click(function (e) {
	            	if(!that.isEditing){
	            		that.currentId = false;
	            	}
	            	
	                commandFn = function () {
	                    $currentTag.remove();
	                };
	                command(e, function () {
	                    setTimeout(hide, 100);
	                });
	            });
	
	            $edit.click(function(e) {
	                var ct = $currentTag;
	                var tagId = $currentTag.attr('data-id');
	                that.currentId = tagId;
	                //rewrite
	                that.isEditing = true;
	                that.tmpData = that.dataJSON[that.currentId].tmpData;
	                that.clearCustomWrap(0);
	                that.layerIn({e:e,editor:editor});
	            });//edit click end
	        }
	        
	        // 显示 toolbar
	        function show() {
	            if (editor._disabled) {
	                // 编辑器已经被禁用，则不让显示
	                return;
	            }
	            if ($currentTag == null) {
	                return;
	            }
	            $(".tags").removeClass('clicked');
	            $currentTag.addClass('clicked');
	            var tagPosition = $currentTag.position();
	            var tagTop = tagPosition.top;
	            var tagLeft = tagPosition.left;
	            var tagHeight = $currentTag.outerHeight();
	            var tagWidth = $currentTag.outerWidth();
	
	            // --- 定位 toolbar ---
	            // 计算初步结果
	            var top = tagTop + tagHeight;
	            var left = tagLeft;
	            var marginLeft = 0;
	
	            var txtTop = $currentTxt.position().top;
	            var txtHeight = $currentTxt.outerHeight();
	            if (top > (txtTop + txtHeight)) {
	                // top 不得超出编辑范围
	                top = txtTop + txtHeight;
	            }
	
	            // 显示（方便计算 margin）
	            $toolbar.show();
	
	            // 计算 margin
	            var width = $toolbar.outerWidth();
	            marginLeft = tagWidth / 2 - width / 2;
	
	            // 定位
	            $toolbar.css({
	                top: top + 5,
	                left: left,
	                'margin-left': marginLeft
	            });
	            // 如果定位太靠左了
	            if (marginLeft < 0) {
	                // 得到三角形的margin-left
	                $toolbar.css('margin-left', '0');
	                $triangle.hide();
	            } else {
	                $triangle.show();
	            }
	        }
	        
	        // 隐藏 toolbar
	        function hide() {
	            if ($currentTag == null) {
	                return;
	            }
	            $toolbar.hide();
	        }
	        
	        // click tag 事件
	        $currentTxt.on('click', '.tags', function (e) {
	            var $tag = $(e.currentTarget);
	
	            // 渲染
	            render();
	
	            // 显示 toolbar
	            $currentTag = $tag;
	            show();
	
	            // 阻止冒泡
	            e.preventDefault();
	            e.stopPropagation();
	            
	        }).on('click keydown scroll', function (e) {
	            setTimeout(hide, 100);
	        });
	        that.WE.$body.on('click keydown scroll', function (e) {
	            setTimeout(hide, 100);
	        });
		},
		
		//获取窗口大小
		getPageSize:function(){var xScroll,yScroll;if(window.innerHeight&&window.scrollMaxY){xScroll=window.innerWidth+window.scrollMaxX;yScroll=window.innerHeight+window.scrollMaxY}else{if(document.body.scrollHeight>document.body.offsetHeight){xScroll=document.body.scrollWidth;yScroll=document.body.scrollHeight}else{xScroll=document.body.offsetWidth;yScroll=document.body.offsetHeight}}var windowWidth,windowHeight;if(self.innerHeight){if(document.documentElement.clientWidth){windowWidth=document.documentElement.clientWidth}else{windowWidth=self.innerWidth}windowHeight=self.innerHeight}else{if(document.documentElement&&document.documentElement.clientHeight){windowWidth=document.documentElement.clientWidth;windowHeight=document.documentElement.clientHeight}else{if(document.body){windowWidth=document.body.clientWidth;windowHeight=document.body.clientHeight}}}if(yScroll<windowHeight){var pageHeight=windowHeight}else{var pageHeight=yScroll}if(xScroll<windowWidth){var pageWidth=xScroll}else{var pageWidth=windowWidth}var arrayPageSize=new Array(pageWidth,pageHeight,windowWidth,windowHeight);return arrayPageSize}
	}//prototype end
	
	var TrueTagsObj = new trueTags().init({
//		debugEnable:false
//		,basePath:'http://61.155.85.74:3333/TrueDPS'
	});
	
	//拓展给jquery
	$.fn.TT = trueTags;
})();